import { login, logout, getInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { staticRoutes, asyncRoutes, myNotFind } from "@/router/routes";
import { resetRouter } from "@/router";
import { cloneDeep } from "lodash";
import router from "@/router";
// let num = 0;
const getDefaultState = () => {
  return {
    token: getToken(),
    name: "",
    avatar: "",
    routes: [],
    menuRoutes: [],
    buttons: [],
  };
};
const getAsyncRouters = (pirmaryArr, conditionArr) =>
  pirmaryArr.filter((item) => {
    if (Array.isArray(item.children)) {
      console.log(conditionArr);

      console.log(item.children);
      //深递归需要对每个数组赋值
      item.children = getAsyncRouters(cloneDeep(item.children), conditionArr);
    }
    return conditionArr.includes(item.name);
  });
const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_MENUROUTES: (state, menuRoutes) => {
    state.menuRoutes = menuRoutes;
  },
  SET_BUTTONS: (state, buttons) => {
    state.buttons = buttons;
  },
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then((response) => {
          const { data } = response;

          commit("SET_TOKEN", data.token);
          setToken(data.token);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then((response) => {
          const { data } = response;
          // console.log("data", data.buttons);

          if (!data) {
            return reject("Verification failed, please Login again.");
          }
          const { name, avatar } = data;

          const resRoutes = data.routes;

          // console.log(state.routes);
          //静态路由
          let menuRoutes = [...staticRoutes];
          //筛选role路由，但没有静态路由
          let outRoutes = getAsyncRouters(cloneDeep(asyncRoutes), resRoutes);
          console.log(outRoutes);
          // menuRoutes = { ...staticRoutes, ...outRoutes };

          // if (num == 0) {
          menuRoutes.push(...outRoutes);

          router.addRoutes(outRoutes);
          router.addRoutes(myNotFind);

          // }
          // num++;

          // console.log(num);

          //导出侧边栏路由

          console.log(router);

          // console.log("router", router.addRoutes);
          // outRoutes.forEach((item) => {
          //   router.addRoute(item.name, item);
          //   console.log("item", item.name);
          // });
          state.routes = resRoutes;
          commit("SET_MENUROUTES", menuRoutes);
          commit("SET_NAME", name);
          commit("SET_AVATAR", avatar);
          commit("SET_BUTTONS", data.buttons);
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken(); // must remove  token  first
          resetRouter();
          commit("RESET_STATE");
          // location.reload();
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
